<?php
/**
 * @package     Email.Plugin
 * @subpackage  Authentication.email
 *
 * @copyright   Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Email Authentication plugin
 *
 * @package     Email.Plugin
 * @subpackage  Authentication.email
 * @since       1.5
 */
class PlgAuthenticationEmail extends JPlugin
{
	/**
	 * This method should handle any authentication and report back to the subject
	 *
	 * @access	public
	 * @param   array  Array holding the user credentials
	 * @param   array  Array of extra options
	 * @param   object	Authentication response object
	 * @return  boolean
	 * @since 1.5
	 */
	public function onUserAuthenticate(&$credentials, $options, &$response)
	{
	  if ($options["action"] != "core.login.site") {
	    return true;
	  }
		$response->type = 'Email';
		$username = $credentials['username'];
		$password = $credentials['password'];
		// Joomla does not like blank passwords
		if (empty($username) || empty($credentials['password']))
		{
			$response->status = JAuthentication::STATUS_FAILURE;
			$response->error_message = JText::_('JGLOBAL_AUTH_INCORRECT');
			return false;
		}

		// Get a database object
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true)
			->select('id, password')
			->from('#__users')
			->where('email=' . $db->quote($credentials['username']));

		$db->setQuery($query);
		$result = $db->loadObject();

		if ($result)
		{
			$parts	= explode(':', $result->password);
			$crypt	= $parts[0];
			$salt	= @$parts[1];
			$testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);

			if ($crypt == $testcrypt)
			{
				$user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
				$credentials['username'] = $user->username;
				$response->username = $user->username;
				$response->email = $user->email;
				$response->fullname = $user->name;
				if (JFactory::getApplication()->isAdmin())
				{
					$response->language = $user->getParam('admin_language');
				}
				else {
					$response->language = $user->getParam('language');
				}
				$response->status = JAuthentication::STATUS_SUCCESS;
				$response->error_message = '';
			} else {
				$response->status = JAuthentication::STATUS_FAILURE;
				$response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
			}
		}
		else
		{
			$response->status = JAuthentication::STATUS_FAILURE;
			$response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
		}
	}
}
